package cn.wellwan.mybatis.utils;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.joda.time.DateTime;

import java.sql.*;

/**
 * creator: maokai
 * on: 2018/3/6
 * description: DateTime 数据类型处理器
 */
//@MappedTypes({org.joda.time.DateTime.class})
//@MappedJdbcTypes({JdbcType.TIMESTAMP})
/*在mapper.xml 中指定哪些类型需要被拦截*/
public class DateTimeTypeHandler extends BaseTypeHandler<DateTime>{
    @Override
    public void setNonNullParameter (PreparedStatement ps , int i , DateTime parameter , JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i,new Timestamp(parameter.getMillis()));
    }

    @Override
    public DateTime getNullableResult (ResultSet rs , String columnName) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnName);
        if(timestamp == null){
            return DateTime.now();
        }
        return new DateTime(timestamp) ;
    }

    @Override
    public DateTime getNullableResult (ResultSet rs , int columnIndex) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnIndex);
        if(timestamp == null){
            return DateTime.now();
        }
        return new DateTime(timestamp) ;
    }

    @Override
    public DateTime getNullableResult (CallableStatement cs , int columnIndex) throws SQLException {
        Timestamp timestamp = cs.getTimestamp(columnIndex);
        if(timestamp == null){
            return DateTime.now();
        }
        return new DateTime(timestamp) ;
    }
}
